<?php
namespace api\admin\controller;

use api\admin\model\BandToiletModel;
use api\admin\model\BandToiletTagModel;
use api\admin\model\ToiletModel;
use api\admin\model\FeedbackModel;
use cmf\controller\RestBaseController;
use think\cache\driver\Redis;
use think\Db;
use think\Validate;

class ToiletController extends RestBaseController
{

    protected $beforeActionList = [
        'getType',
        'toiletcheck' => ['only' => 'addtoilet'],
    ];

    /**
     * [getType 前置操作]
     * @Author   HUI
     * @DateTime 2018-11-26
     * @version  [version]
     * @param    string     $value [description]
     */
    public function getType($value = '')
    {
        if ($this->getUserType() !== 3) {
            $this->error('暂无创建权限');
        }
    }

    public function test($value = '')
    {
        $ks = 'H2S_woman';
        // $ks = strpos($ks,'H') ? 'H2S':$ks;
        $a = substr_count(($ks), 'H2S');
        print_r($a);
        exit();
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $result = $redis->hgetall('cloud_00ff2c2c2c6a6f005f94');
        foreach ($result as $key => $value) {
            $toiletTmp = unserialize($value);
            foreach ($toiletTmp as $k => $v) {
                if (!empty($k)) {
                    $tmp = @unserialize($v);
                    $toilet[$key][] = $tmp;
                }
            }
        }
        $toilet = $this->arrayToSort($toilet);
        return $toilet;
    }

    //获取用户随机码
    // public function getUserCodes()
    // {
    //     return $this->getUserCode();
    // }
    /**
     * [arrayToSort description]
     * @Author   HUI
     * @DateTime 2018-12-03
     * @version  [version]
     * @param    string     $value [description]
     */
    public function arrayToSort($toilet = '')
    {
        foreach ($toilet as $key => $value) {
            $toilet[$key] = $this->Tosort($value);
        }
        return $toilet;
    }

    /**
     * [toVersion 应用接口]
     * @Author   HUI
     * @DateTime 2018-12-04
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function updateVersion($value = '')
    {
        $param = $this->request->param();
        $Toilet = new ToiletModel();
        if ($Toilet->where('id', $param['id'])->setInc('version')) {
            $redis = new Redis();
            $r = $redis->get($param['mac'] . '_version');
            if (!$r) {
                $redis->set($param['mac'] . '_version',2);
            } else {
                if ($redis->inc($param['mac'] . '_version')) {
                    $this->success('操作成功');
                }

            }
        }
        $this->error('操作失败');
    }
    /**
     * 数组排序
     * @Author   HUI
     * @DateTime 2018-12-03
     * @version  [version]
     * @param    string     $value [description]
     */
    public function ToSort($value = '')
    {
        array_multisort(array_column($value, 'order'), SORT_ASC, $value);
        return $value;
    }

    /**
     * [add_toilet_check 检测可添加公厕数量]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     */
    public function toiletcheck($value = '')
    {
        $this->getDeviceNum();
    }

    /**
     * [addToilet 添加公厕]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     */
    public function addtoilet($value = '')
    {

        $validate = new Validate([
            'title' => 'require',
            'man_num' => 'require',
            'woman_num' => 'require',
        ]);
        $validate->message([
            'title.require' => '公厕名称不能为空',
            'man_num.require' => '男厕数量不能为0!',
            'woman_num.require' => '女厕数量不能为0!',
        ]);

        $data = $this->request->param();
        //if (!$validate->check($data)) {
        //    $this->error($validate->getError());
        //}
        // print_r($data);exit();
        // $data['flow'] = [3,4];
        // $data['sensor'] = [3,4];


        //获取用户ID
        $user_id = $this->getUserId();
        $Toilet = new ToiletModel();
        $feedback = new FeedbackModel();


        //添加事务
        Db::startTrans();
        try {

            $flow_num = isset($data['flow']) && !empty($data['flow']) ? count($data['flow']) : 0;
            $sensor_num = isset($data['sensor']) && !empty($data['sensor']) ? count($data['sensor']) : 0;
            // print_r($flow_num);
            // print_r($sensor_num);
            // exit();
            $insertData = [
                'title' => $data['title'],
                'position' => $data['position'],
                'man_num' => $data['man_num'],
                'woman_num' => $data['woman_num'],
                'third_num' => $data['third_num'],
                'child_num' => $data['child_num'],
                'disability_num' => $data['disability_num'],
                'infant_num' => $data['infant_num'],
                'start_time' => $data['start_time'],
                'end_time' => $data['end_time'],
                'sensor_num' => $sensor_num,
                'flow_num' => $flow_num,
                'user_id' => $this->getUserId(),
                'create_time' => time(),
            ];

            $tid = $Toilet->insertGetId($insertData);
            //添加流量信息
            if ($flow_num) {
                $res = $Toilet->dataInsertBand($data['flow'], 1, $tid);

            }
            //添加红外信息
            if ($sensor_num) {
                $res = $Toilet->dataInsertBand($data['sensor'], 3, $tid);
            }

            //添加一条反馈
            $feedback->insertFeedbackData($tid,$user_id);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('添加失败');
        }

        $this->success('添加成功',['toilet_id'=>$tid]);
    }

    //获取其他设备--不区分男女第二版
    public function getOtherDevicev2()
    {
        $id = $this->request->param('id');
        $Toilet = new ToiletModel();
        $result = $Toilet->getToiletFields($id,'mac');

        
        $Band = new BandToiletModel();
        $data = $Band->
        where(['t_id' => $id, 'mac_device_type' => ['IN',[4,5,6,7,8]]])
        ->select();

        $arr = [
            '4'=>'smoke',
            '5'=>'water',
            '6'=>'electric',
            '7'=>'sos',
            '8'=>'wateryield',
        ];

        $resArr = [];
        foreach ($data as $key => $value) {

            $resArr[$arr[$value['mac_device_type']]] = $value['mac'];
        }

        $this->success('获取成功',$resArr);

    }


    //添加其他设备--不区分男女第二版
    public function addOtherDevicev2()
    {

        $validate = new Validate([
            'id' => 'require',
        ]);
        $validate->message([
            'id.require' => '请先添加主坑位',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        // print_r($data);exit();

        $tid = $data['id'];
        $Toilet = new ToiletModel();
        $toiletRes = $Toilet->where('id',$tid)->find();
        $masterMac = $toiletRes['mac'];
        //烟感
        $Smoke = isset($data['smoke']) && !empty($data['smoke']) ? count($data['smoke']) : 0;
        //水浸
        $Water = isset($data['water']) && !empty($data['water']) ? count($data['water']) : 0;
        //电量
        $Electric = isset($data['electric']) && !empty($data['electric']) ? count($data['electric']) : 0;

        $sos = isset($data['sos']) && !empty($data['sos']) ? count($data['sos']) : 0;

        $wateryield = isset($data['wateryield']) && !empty($data['wateryield']) ? count($data['wateryield']) : 0;

        

        $Band = new BandToiletModel();
        // $Band->where(['t_id' => $tid, 'mac_device_type' => ['IN',[4,5,6,7]]])->delete();

        $Toilet->where('id',$tid)->update([
            'smoke_num'=>$Smoke,
            'water_num'=>$Water,
            'electric_num'=>$Electric,
            'sos_num'=>$sos,
            'wateryield_num'=>$wateryield,
        ]);


        $res = 0;
        if ($Smoke) {


            $res = $Band->save([
                't_id'=>$tid,
                'tag_id'=>9,
                'mac'=>$data['smoke'],
                'mac_device_type'=>4,
                'create_time'=>time()
            ]);

        }
        if ($Water) {


            $res = $Band->save([
                't_id'=>$tid,
                'tag_id'=>9,
                'mac'=>$data['water'],
                'mac_device_type'=>5,
                'create_time'=>time()
            ]);

            // $res = $Band->dataInsertBand(['water'=>$data['water']],$tid,$masterMac);
            // $res = $Toilet->dataInsertBand($data['water'], 5,$tid,$masterMac);
        }

        if ($Electric) {


            $res = $Band->save([
                't_id'=>$tid,
                'tag_id'=>9,
                'mac'=>$data['electric'],
                'mac_device_type'=>6,
                'create_time'=>time()
            ]);

            // $res = $Band->dataInsertBand(['electric'=>$data['electric']],$tid,$masterMac);
        }

        if ($sos) {

            $res = $Band->save([
                't_id'=>$tid,
                'tag_id'=>9,
                'mac'=>$data['sos'],
                'mac_device_type'=>7,
                'create_time'=>time()
            ]);

            // $res = $Band->dataInsertBand(['sos'=>$data['sos']],$tid,$masterMac);
        }


        if ($wateryield) {


            $res = $Band->save([
                't_id'=>$tid,
                'tag_id'=>9,
                'mac'=>$data['wateryield'],
                'mac_device_type'=>8,
                'create_time'=>time()
            ]);

            // $res = $Band->dataInsertBand(['wateryield'=>$data['wateryield']],$tid,$masterMac);
        }


        if (!$res) {
            $this->error('创建失败');
        }
        $this->success('创建成功');


    }

    /**
     * [addOtherDevice 添加其他设备]
     * @Author   Hui
     * @DateTime 2019-01-24
     * @version  [version]
     * @param    string
     */
    public function addOtherDevice($value='')
    {

        $validate = new Validate([
            'id' => 'require',
        ]);
        $validate->message([
            'id.require' => '请先添加主坑位',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        // print_r($data);exit();

        $tid = $data['id'];
        $Toilet = new ToiletModel();
        $toiletRes = $Toilet->where('id',$tid)->find();
        $masterMac = $toiletRes['mac'];
        //烟感
        $Smoke = isset($data['smoke']) && !empty($data['smoke']) ? count($data['smoke']) : 0;
        //水浸
        $Water = isset($data['water']) && !empty($data['water']) ? count($data['water']) : 0;
        //电量
        $Electric = isset($data['electric']) && !empty($data['electric']) ? count($data['electric']) : 0;

        $sos = isset($data['sos']) && !empty($data['sos']) ? count($data['sos']) : 0;

        $wateryield = isset($data['wateryield']) && !empty($data['wateryield']) ? count($data['wateryield']) : 0;

        

        $Band = new BandToiletModel();
        // $Band->where(['t_id' => $tid, 'mac_device_type' => ['IN',[4,5,6,7]]])->delete();

        $Toilet->where('id',$tid)->update([
            'smoke_num'=>$Smoke,
            'water_num'=>$Water,
            'electric_num'=>$Electric,
            'sos_num'=>$sos,
            'wateryield_num'=>$wateryield,
        ]);


        $res = 0;
        if ($Smoke) {
            $res = $Band->dataInsertBand(['smoke'=>$data['smoke']],$tid,$masterMac);
        }
        if ($Water) {
            $res = $Band->dataInsertBand(['water'=>$data['water']],$tid,$masterMac);
            // $res = $Toilet->dataInsertBand($data['water'], 5,$tid,$masterMac);
        }

        if ($Electric) {
            $res = $Band->dataInsertBand(['electric'=>$data['electric']],$tid,$masterMac);
        }

        if ($sos) {
            $res = $Band->dataInsertBand(['sos'=>$data['sos']],$tid,$masterMac);
        }


        if ($wateryield) {
            $res = $Band->dataInsertBand(['wateryield'=>$data['wateryield']],$tid,$masterMac);
        }


        if (!$res) {
            $this->error('创建失败');
        }
        $this->success('创建成功');
    }

    /**
     * [getToiletDetails 获取公厕基本信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getToiletDetails($value = '')
    {

        $id = $this->request->param("id");
        $Toilet = new ToiletModel();
        return $this->success('获取成功', ['details' => $Toilet->getToiletJoinFields(['id' => $id, 'user_id' => $this->getUserId()])]);
    }

    /**
     * [getOtherToiletDetails 获取其他设备详情及信息]
     * @Author   Hui
     * @DateTime 2019-01-28
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getOtherToiletDetails($value='')
    {
        $id = $this->request->param('id');
        $Toilet = new ToiletModel();
        $result = $Toilet->getToiletFields($id,'mac');
        // $masterMac = $result['mac'];
        $smoke = $Toilet->getRedisData($id, 4);
        $water = $Toilet->getRedisData($id, 5);
        $electric = $Toilet->getRedisData($id, 6);
        $sos = $Toilet->getRedisData($id, 7);
        $smokeArr = $this->getToiletEasy($smoke);
        $waterArr = $this->getToiletEasy($water);
        $electricArr = $this->getToiletEasy($electric);
        $sosArr = $this->getToiletEasy($sos);
        // $toilet = array_merge($smokeArr,$waterArr,$electricArr,$sosArr);
        $this->success('获取成功', ['smoke' => $smokeArr,'water'=>$waterArr,'electric'=>$electricArr,'sos'=>$sosArr]);
    }

    /**
     * [FunctionName ]
     * @Author   Hui
     * @DateTime 2019-01-28
     * @version  [version]
     * @param    string     $value [description]
     */
    public function getToiletEasy($data)
    {

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);

        $toilet = [];
        if (!empty($data)) {

            foreach ($data as $key => $value) {
                $res = $this->appGetRedisKey($value);
                //print_r($res);exit;
                $redisRes = $redis->hgetall($res);
                //print_r($redisRes);
                $tmpArr = explode('_',$res);
                $rediskyes = $tmpArr[count($tmpArr)-2].'_'.$tmpArr[count($tmpArr)-1];
                //print_r($rediskyes);exit;
                if (is_array($redisRes)) {
        	    foreach ($redisRes as $keys => $values) {
	        	$redisRes = $values;
        	    }
                }
		//print_r(unserialize($redisRes));
                if ($redisRes) {
                    $va = isset(unserialize($redisRes)['zsta']) ? unserialize($redisRes)['zsta'] :unserialize($redisRes)['dianliang'];
                }else{
                    $va = 0;
                }
                $toilet[$rediskyes]['vals'] = $va;
                $toilet[$rediskyes]['mac'] = $value['mac'];
            }
        }

        return $toilet;

    }


        /**
     * [getRedisKey 根据数据生成键名]
     * @Author   HUI
     * @DateTime 2018-12-03
     * @version  [version]
     * @param    array      $array [description]
     * @return   [type]            [description]
     */
    public function appGetRedisKey($array = [])
    {
        // cloud_mac 此MAC所有信息
        // cloud_mac_device 此MAC设备类型下的所有信息
        // cloud_mac_device_man 此MAC设备类型男厕下的所有信息
        // cloud_mac_device_man_mini[mac] 此MAC设备类型男厕下单设备的信息
        $mac_device_type = ['flow','device','sensor','smoke','water','electric','sos'];
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $Tag = $redis->get('toiletTag');
        // print_r($Tag);exit;
        foreach (unserialize($Tag) as $key => $value) {
            if ($array['tag_id'] == $value['id']) {
                $device = $value;
            }
        }
        if (empty($device)) {
            return 0;
        }
        //1.tag写入缓存
        //2.主设备状态写入缓存 5min
        //2.单设备状态写入缓存 5min
        return 'cloud_' . $array['master_mac'] . '_' . $mac_device_type[$array['mac_device_type'] - 1] . '_' . $device['tag_as_name'];
    }

    /**
     * [getToiletlist 获取当前用户列表]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getToiletlist($value = '')
    {
        
        $param = $this->request->param();
        $Toilet = new ToiletModel();
        if ($this->request->isPost() && !empty($param['keywords'])) {
            $result = $Toilet->where(['user_id' => $this->getUserId(), 'title' => ['like', "%{$param['keywords']}%"], 'status' => '1'])->paginate(10);
        } else {
            $result = $Toilet->where(['user_id' => $this->getUserId(), 'status' => '1'])->paginate(10);
        }
        foreach ($result as $key => $value) {
            $value['cloud_status'] = $Toilet->getCloudStatus($value['mac']);
            $result[$key] = $value;
        }
        return $this->success('获取成功', ['details' => $result
            , 'device' => $this->getDeviceCountNum(), 'show_code' => $this->getUserCode(),
        ]);
    }

    /**
     * [toiletDel 删除公厕]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function toiletDel($value = '')
    {
        $id = $this->request->param('id');
        $BandToilet = new BandToiletModel();

        $BandToilet->where(['t_id' => $id])->delete();

        $Toilet = new ToiletModel();
        $result = $Toilet
        ->updateToiletFields(['id' => $id, 'user_id' => $this->getUserId()], ['status' => 0]);
        // print_r($result);exit();
        if ($result) {
            $this->success('删除成功');
        }else{
            $this->error('请先删除绑定');
        }
    }

    /**
     * [editToilet 编辑当前公厕]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function editToilet($value = '')
    {
        $validate = new Validate([
            'title' => 'require',
            'man_num' => 'require',
            'woman_num' => 'require',
        ]);
        $validate->message([
            'title.require' => '公厕名称不能为空',
            'man_num.require' => '男厕数量不能为0!',
            'woman_num.require' => '女厕数量不能为0!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        // print_r($data);exit();
        $Toilet = new ToiletModel();
        $ToiletRes = $Toilet->where(['id' => $data['id'], 'user_id' => $this->getUserId()])->find();
        if (empty($ToiletRes)) {
            $this->error('error');
        }

        //查询是否存在投诉
        // $feedback = new FeedbackModel();
        // $fexist = $feedback->where(['t_id'=>$data['id']])->find();
        // if (empty($fexist)) {
        //     $feedback->insert(['t_id'=>$data['id'],'create_time'=>time()]);
        // }



        //统计接受到的数据
        $data['flow_num'] = isset($data['flow']) && !empty($data['flow']) ? count($data['flow']) : 0;
        $data['sensor_num'] = isset($data['sensor']) && !empty($data['sensor']) ? count($data['sensor']) : 0;
        // //烟感
        // $Smoke = isset($data['smoke']) && !empty($data['smoke']) ? count($data['smoke']) : 0;
        // //水浸
        // $Water = isset($data['water']) && !empty($data['water']) ? count($data['water']) : 0;
        // //电量
        // $Electric = isset($data['electric']) && !empty($data['electric']) ? count($data['electric']) : 0;



        // $ToiletTmp = ['man_num', 'woman_num', 'third_num', 'child_num', 'disability_num', 'infant_num', 'flow_num', 'sensor_num'];
        $ToiletTmp = ['man_num', 'woman_num', 'third_num', 'child_num', 'disability_num', 'infant_num'];
        //判断数据库是否一致
        foreach ($ToiletTmp as $key => $value) {

            if ($ToiletRes[$value] != $data[$value]) {
                
                $Toilet->bandDelDevice($value, $data['id']);
            }
        }

        $Band = new BandToiletModel();

        Db::startTrans();
        try {
            $flow_num = isset($data['flow_num']) ? $data['flow_num']:[];
            $sensor_num = $data['sensor_num'];
            $insertData = [
                'title' => $data['title'],
                'position' => $data['position'],
                'man_num' => $data['man_num'],
                'woman_num' => $data['woman_num'],
                'third_num' => $data['third_num'],
                'child_num' => $data['child_num'],
                'disability_num' => $data['disability_num'],
                'infant_num' => $data['infant_num'],
                'start_time' => $data['start_time'],
                'end_time' => $data['end_time'],
                'post_code' => !empty($data['post_code']) ? $data['post_code'] : 0 ,
                'sensor_num' => $sensor_num,
                'flow_num' => $flow_num,
                // 'smoke_num'=>$Smoke,
                // 'water_num'=>$Water,
                // 'electric_num'=>$Electric,
                // 'thumbnail' => json_encode($data['thumbnail']),
                // 'notice' => $data['notice'],
                'user_id' => $this->getUserId(),
                'create_time' => time(),
            ];

            $result = $Toilet->where('id', $data['id'])->update($insertData);
            $resData = [
                'sensor'=>$data['sensor'],
                'flow'=>$data['flow']
            ];
            //编辑绑定的男女厕关系
            $Band->dataInsertBand($resData,$data['id']);



            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }


    /**
     * [updateNotice 获取更新公告]
     * @Author   HUI
     * @DateTime 2018-12-01
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function updateNotice($value = '')
    {

        $validate = new Validate([
            'thumbnail' => 'require',
            'notice' => 'require',
        ]);
        $validate->message([
            'notice.require' => '公告不能为空!',
            'thumbnail.require' => '图片不能为空',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        if (!empty($data['music_url']) && count($data['music_url']) > 3) {
            $this->error('上传音乐不能超过3条');
        }
        
        $updateData = [
            'music_url' => !empty($data['music_url']) ? json_encode($data['music_url']):'',
            'thumbnail' => !empty($data['thumbnail']) ? json_encode($data['thumbnail']):'',
            'notice' => $data['notice'],
        ];
        $Toilet = new ToiletModel();
        if ($Toilet->where('id', $data['id'])->update($updateData)) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }

    }

    /**
     * [bandToilet 绑定公厕设备]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function bandToilet($value = '')
    {

        $validate = new Validate([
            'mac' => 'require',
        ]);
        $validate->message([
            'mac.require' => '网关地址不能为空',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $Toilet = new ToiletModel();
        $count = $Toilet->where(['id' => $data['id'], 'user_id' => $this->getUserId(), 'mac' => $data['mac']])->count();
        if ($count > 1) {
            return $this->error('mac重复使用,请先删除..');
        }
        $Toilet->updateToiletFields(['id' => $data['id'], 'user_id' => $this->getUserId()], ['mac' => $data['mac']]);
        $Band = new BandToiletModel();
        foreach ($data as $key => $value) {
            switch ($key) {
                case 'sensor':
                    //传感器设备
                    $res = $Band->bandToMac($value, $data['mac']);
                    break;
                case 'flow':
                    //流量设备
                    $res = $Band->bandToMac($value, $data['mac']);
                    break;
                case 'smoke':
                    //烟感设备   smoke water  electric
                    $res = $Band->bandToMac($value, $data['mac']);
                    break;
                case 'water':
                    //电表设备
                    $res = $Band->bandToMac($value, $data['mac']);
                    break;
                case 'electric':
                    //水浸设备
                    $res = $Band->bandToMac($value, $data['mac']);
                    break;
                case 'sos':
                    //水浸设备
                    $res = $Band->bandToMac($value, $data['mac']);
                    break;
                default:
                    if (is_array($value)) {
                        $exists = array_key_exists('id', $Band->objectArray(json_decode(htmlspecialchars_decode(htmlspecialchars_decode($value[0])))));
                        $res = $Band->bandDevToMac($value, $data['id'], 2, $data['mac'], $exists, $key);
                    }
                    break;
            }

        }
        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * [getToiletTag 获取公厕类型]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getToiletTag($value = '')
    {
        $Tag = new BandToiletTagModel();
        return $this->success('获取成功', ['list' => $Tag->select()]);
    }

    /**
     * [bandChange 更新绑定MAC]
     * @Author   HUI
     * @DateTime 2018-11-28
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function bandChange($value = '')
    {
        $validate = new Validate([
            'mac' => 'require',
        ]);
        $validate->message([
            'mac.require' => 'MAC不能为空',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $Band = new BandToiletModel();
        $Toilet = new ToiletModel();
        $toi = $Toilet->getToiletFields(['id' => $data['t_id'], 'user_id' => $this->getUserId()]);
        if (!empty($toi)) {
            if ($Band->updateBandToiletFields(['id' => $data['id'], 't_id' => $data['t_id']], ['mac' => $data['mac']])) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        } else {
            $this->error('更新失败');
        }

    }

    /**
     * [bandMacDel 删除绑定mac]
     * @Author   HUI
     * @DateTime 2018-11-28
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function bandMacDel($value = '')
    {
        $validate = new Validate([
            'mac' => 'require',
        ]);
        $validate->message([
            'mac.require' => 'MAC不能为空',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $Band = new BandToiletModel();
        $Toilet = new ToiletModel();
        $toi = $Toilet->getToiletFields(['id' => $data['t_id'], 'user_id' => $this->getUserId()]);

        Db::startTrans();
        try {
            $bandRes = $Band->where(['id' => $data['id'], 't_id' => $data['t_id']])->find();
            switch ($bandRes['mac_device_type']) {
                case '1':
                    $num = 'flow_num';
                    break;
                case '3':
                    $num = 'sensor_num';
                    break;
                default:
                    switch ($bandRes['tag_id']) {
                        case '3':
                            $num = 'man_num';
                            break;
                        case '4':
                            $num = 'woman_num';
                            break;
                        case '5':
                            $num = 'infant_num';
                            break;
                        case '6':
                            $num = 'disability_num';
                            break;
                        case '7':
                            $num = 'third_num';
                            break;
                        default:
                            $num = 'child_num';
                            break;
                    }
                    break;
            }
            $Toilet->where('id', $data['t_id'])->setDec($num);
            $Band->where(['id' => $data['id'], 't_id' => $data['t_id']])->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('删除失败');
        }
        $this->success('删除成功');

    }

    /**
     * [getMacData 获取当前mac的所有值]
     * @Author   HUI
     * @DateTime 2018-11-29
     * @version  [version]
     * @param    [type]     $mac [description]
     * @return   [type]          [description]
     */
    public function getMacData($mac)
    {
        $result = $redis->hgetall('cloud_' . $mac);

    }

    /**
     * [addToiletTag 添加tag缓存]
     * @Author   HUI
     * @DateTime 2018-12-03
     * @version  [version]
     * @param    string     $value [description]
     */
    public function addToiletTag($value = '')
    {
        $Tag = new BandToiletTagModel();
        return $this->success('缓存设置成功', ['status' => $Tag->addToiletTags()]);
    }

}
